package com.hexus.eve.utils;

import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import javax.annotation.PostConstruct;

import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hexus.eve.entities.Type;

/**
 * Spring singletone bean which contains map of all types 
 * and provide all functionality required regarding types
 * 
 * @author Mikhail_Berastau 
 */
@SuppressWarnings("restriction")
@Service
public class TypeUtils {
	private Logger log = Logger.getLogger(this.getClass());
	
	@Autowired
	private SessionFactory sessionFactory;
	
	private static TypeUtils instance;
	
	/**
	 * Map of all types, where value is a type and id is this type's id.</br>
	 * Serves for fast getting type by it's id. 
	 */
	private static HashMap<Integer, Type> typesMap = new HashMap<Integer, Type>();
	
	private TypeUtils(){
		instance = this;
	}
	
	public static TypeUtils getInstance() {
		return instance;
	}
	
	@SuppressWarnings({ "unused" })
	@PostConstruct
	private void init() {
		Date timer = new Date();
		if(log.isDebugEnabled()) {
			log.debug("Initializing Types bean...");
		}
		
		Session session = sessionFactory.openSession();
		try {
			
			@SuppressWarnings("rawtypes")
			//Getting all types
			Iterator iter = session.createQuery("from Type where published = 1").iterate();
			while(iter.hasNext()) {
				Type type = (Type)iter.next();
				typesMap.put(type.getId(), type);
			}
			
			if(log.isDebugEnabled()) {
				log.debug("The Types bean is initialized. " + typesMap.size() + " types are loaded in " + ((new Date()).getTime() - timer.getTime()) / 1000 + " seconds.");
			}
		}
		catch(Exception ex) {
			log.error(ex.getMessage());
			ex.printStackTrace();
		}
		finally {
			session.close();
		}
		
	}
	
	public Type getType(Integer id) {
		return typesMap.get(id);
	}
}
